package com.limao.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Random;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.patchca.color.ColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.filter.predefined.DiffuseRippleFilterFactory;
import org.patchca.filter.predefined.DoubleRippleFilterFactory;
import org.patchca.filter.predefined.MarbleRippleFilterFactory;
import org.patchca.filter.predefined.WobbleRippleFilterFactory;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;

import com.alibaba.fastjson.JSON;
import com.limao.Model.PublicData;
import com.limao.Tool.CacheClass;

public class OutPrintClass {
	/*	
	public static String readJSONString(HttpServletRequest request) {

		String json = request.getParameter("data");
		
		System.out.println(json);
		
		return json;
		
	}
	
	*/
	private static ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
	private static Random random = new Random();
	
	public static String readJSONString(HttpServletRequest request) {
		 
		
		
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
			line=null;
			return line;
		}
		try {
			 line=json.toString();
			 line=URLDecoder.decode(line, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			line=null;
			return line;
		}
		

		 if(line.startsWith("data="))
			 line=line.substring(5, line.length());
		 CacheClass.Println(CacheClass.getFormatDate(new Date(), "yyyy-MM-dd HH:mm:ss")+"  收到:"+line);
		
		return line;
		
	}
	
	public	static	void writer(HttpServletResponse response, Object obj){
		writer(response,obj,null);
	}
	
	public	static	void writer(HttpServletResponse response, Object obj,AsyncContext asyncContext){
		initReponse(response);
		PrintWriter pw = null;
		try{
		
			pw=response.getWriter();
			
			String str=JSON.toJSONString(obj);
			
			pw.write(str);
			
			CacheClass.Println("返回:"+str);
			
		} catch (IOException e){
			
			if(asyncContext!=null)
				asyncContext.complete();
			throw new RuntimeException(e);
		}
		finally {
			if(asyncContext!=null)
				asyncContext.complete();
		}
		 
	}

	
	private static void setResponseHeaders(HttpServletResponse response) {
		response.setContentType("image/png");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);
	}
	
	public	static	void writerNoJson(HttpSession session,HttpServletResponse response,AsyncContext asyncContext){
		try{
			cs.setColorFactory(new ColorFactory() {
				@Override
				public java.awt.Color getColor(int x) {
					int[] c = new int[3];
					int i = random.nextInt(c.length);
					for (int fi = 0; fi < c.length; fi++) {
						if (fi == i) {
							c[fi] = random.nextInt(71);
						} else {
							c[fi] = random.nextInt(256);
						}
					}
					return new java.awt.Color(c[0], c[1], c[2]);
				}
			});
			RandomWordFactory wf = new RandomWordFactory();
			wf.setCharacters("23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
			wf.setMaxLength(4);
			wf.setMinLength(4);
			cs.setWordFactory(wf);

			switch (random.nextInt(5)) {
			case 0:
				cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
				break;
			case 1:
				cs.setFilterFactory(new MarbleRippleFilterFactory());
				break;
			case 2:
				cs.setFilterFactory(new DoubleRippleFilterFactory());
				break;
			case 3:
				cs.setFilterFactory(new WobbleRippleFilterFactory());
				break;
			case 4:
				cs.setFilterFactory(new DiffuseRippleFilterFactory());
				break;
			}
			setResponseHeaders(response);
			String code = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
			session.setAttribute("code", code);
		} catch (Exception e){
			
			if(asyncContext!=null)
				asyncContext.complete();
			throw new RuntimeException(e);
		}
		finally {
			if(asyncContext!=null)
				asyncContext.complete();
		}
		 
	}
	
	
	
	public	static	void writerNoJson(HttpSession session,HttpServletResponse response){
		try{
			cs.setColorFactory(new ColorFactory() {
				@Override
				public java.awt.Color getColor(int x) {
					int[] c = new int[3];
					int i = random.nextInt(c.length);
					for (int fi = 0; fi < c.length; fi++) {
						if (fi == i) {
							c[fi] = random.nextInt(71);
						} else {
							c[fi] = random.nextInt(256);
						}
					}
					return new java.awt.Color(c[0], c[1], c[2]);
				}
			});
			RandomWordFactory wf = new RandomWordFactory();
			wf.setCharacters("23456789abcdefghigkmnpqrstuvwxyzABCDEFGHIGKLMNPQRSTUVWXYZ");
			wf.setMaxLength(4);
			wf.setMinLength(4);
			cs.setWordFactory(wf);

			switch (random.nextInt(5)) {
			case 0:
				cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
				break;
			case 1:
				cs.setFilterFactory(new MarbleRippleFilterFactory());
				break;
			case 2:
				cs.setFilterFactory(new DoubleRippleFilterFactory());
				break;
			case 3:
				cs.setFilterFactory(new WobbleRippleFilterFactory());
				break;
			case 4:
				cs.setFilterFactory(new DiffuseRippleFilterFactory());
				break;
			}
			setResponseHeaders(response);
			String code = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
			session.setAttribute("code", code);
		} catch (Exception e){
			throw new RuntimeException(e);
		}
		 
	}
	

	public static Object resultObj(int m,String info){
		PublicData data =new PublicData();
		data.m =m+"";
		data.state = "1";
		data.info = info;
		return data;
	}
	
	
	public static Object errorObj(int m,String info){
		PublicData data =new PublicData();
		data.m =m+"";
		data.state = "0";
		data.info = info;
		return data;
	}  
	


	private static void initReponse(HttpServletResponse response) {
		response.setContentType("text/json;charset=UTF-8");
		response.setHeader("Cache-Control","no-cache");

	}
	
	
	
	public	static	Object read(String dataStr,Class<?> T)
	{
		return JSON.parseObject(dataStr, T);
	}
	
	
	
	
	public	static	void sendError(HttpServletResponse response,AsyncContext asyncContext,int m,String info)
	{
		PublicData data =new PublicData();
		data.state = "0";
		data.info = info;
		data.m=m+"";
		writer(response, data, asyncContext);
		data=null;
		return;
	}
	//系统维据中
	public	static	void sendMaintenance(HttpServletResponse response,AsyncContext asyncContext,int m,String info)
	{
		PublicData data =new PublicData();
		data.state = "99";
		data.info = info;
		data.m=m+"";
		writer(response, data, asyncContext);
		data=null;
		return;
	}
	
	public	static	void sendResult(HttpServletResponse response,AsyncContext asyncContext,int m,String info)
	{
		PublicData data=new PublicData();
		data.m=m+"";
		data.info=info;
		data.state="1";
		writer(response,data,asyncContext);
		data=null;
	}	
	
	public	static	void sendResult(HttpServletResponse response,AsyncContext asyncContext,PublicData data)
	{
		writer(response,data,asyncContext);
		data=null;
	}	
		
}
